import {login,getUserInfo} from "./login.js"
import store from '../store/index.js';

let baseUrl;
if (process.env.NODE_ENV === 'development') {
	console.log('开发环境');
	baseUrl = 'http://feitu.cn/api/';
} else {
	console.log('生产环境');
	baseUrl = 'https://feitu.smartspark.xyz/api/';
}
export { baseUrl };

function httpRequest(obj) {
    let token = uni.getStorageSync('token')
    return new Promise( (resolve, reject)=> {
        uni.request({
			url: obj.url,
			data: obj.data,
			method: obj.method,
			header: {
				"Content-Type": "application/json",
				token: token,
				apptype: 'merchant_xcc',
			},
			dataType: 'json',
		}).then(async(response) => {
			// 重新登录，再次请求
			if(response.statusCode === 401){
				uni.clearStorageSync();
				store.commit('logout');
				throw new Error('Unauthorized');
				return;
			}
			if(response.statusCode !== 200){
				uni.showToast({title: '请求失败，请稍后重试！', icon:'none'});
				reject(new Error('Request failed'));
				return
			}
			
			const data = response.data;
			// 重新登录，再次请求
			if(data.code==401){
				uni.clearStorageSync();
				store.commit('logout');
				throw new Error('Unauthorized');
				return
			}
			if(data.code==1){
				resolve(data.data)
			}else{
				uni.showToast({title: data.info, icon:'none'});
				reject(new Error(data.info));
				return
			}
        }).catch(async(error) => {
			console.log(error.message)
			// 如果是登录失效，登录后重试
			if(error.message == 'Unauthorized'){		
				login().then(()=>{
					console.log('Unauthorized, relogin')
					reRequest(obj).then(res=>{
						resolve(res)
					}).catch(error =>{
						reject(error)
					})
				}) 
			}else{
				reject(error)
			}
		}) 
    }) 
};

// 重复请求
function reRequest(obj) {
	let token = uni.getStorageSync('token')
	return new Promise((resolve, reject)=> {
	    uni.request({
			url: obj.url,
			data: obj.data,
			method: obj.method,
			header: {
				"Content-Type": "application/json",
				token: token,
				apptype: 'merchant_xcc',
			},
			dataType: 'json',
		}).then((response) => {
			// 跳转首页
			if(response.statusCode === 401){
				uni.clearStorageSync();
				reject(new Error('Unauthorized'));
				return;
			}
			if(response.statusCode !== 200){
				uni.showToast({title: '请求失败，请稍后重试！', icon:'none'});
				reject(new Error('Request failed'));
				return
			}
			const data = response.data;
			// 跳转首页，重新登录
			if(data.code==401){
				uni.clearStorageSync();
				reject(new Error('Unauthorized'));
				return
			}
			if(data.code==1){
				resolve(data.data)
			}else{
				uni.showToast({title: data.info, icon:'none'});
				reject(new Error(data.info));
				return
			}
	    }).catch((error) => {
			reject(error)
		})
	}) 
}

export const get = (url) =>  httpRequest({
	url: baseUrl + url,
	data: {},
	method: 'GET'
})

export const post = (url, data={}) =>  httpRequest({
	url: baseUrl + url,
	data: data,
	method: 'POST'
})

export default {
	baseUrl,
	get,
	post
}